﻿using AntdUI;
using EONFULLSIN.Common.App;
using EONFULLSIN.Controls;
using EONFULLSIN.Languages;
using EONFULLSIN.Models;
using EONFULLSIN.Models.Entity.Log;
using EONFULLSIN.Models.Entity.User;
using EONFULLSIN.Models.Enum;
using EONFULLSIN.Utils;
using EONFULLSIN.Views;
using EONFULLSIN.Views.Manual;
using EONFULLSIN.Views.SubView;
using EONFULLSIN.Views.UserView;
using Microsoft.Win32;
using NLog.Filters;
using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Menu = AntdUI.Menu;
using MenuItem = AntdUI.MenuItem;
using User = EONFULLSIN.Models.Entity.User.User;

namespace EONFULLSIN
{
    public partial class MainWindow : AntdUI.Window
    {
        private UserControl control;
        private AntdUI.Window Window;

        public MainWindow()
        {
            InitializeComponent();
            LanguageChangedEvent.LanguageChanged += UpdateLanguage;
            //加载配置文件
            LoadAppConfig();
            //加载菜单
            LoadMenu();
            //加载欢迎页
            InitData();
            //绑定事件
            BindEventHandler();
            UpdateLanguage(LanguageHelper.CurrentLanguage);
        }

        private void UpdateLanguage(string language)
        {
            input_search.PlaceholderText = LanguageHelper.GetTranslation(language, "MainFormInputSearch");
            var user = menu_user.Items.Find(x => x.ID.Equals("LoginStatus"));
            //user.Text = LanguageHelper.GetTranslation(language, "LoginStatus");
            user.Sub.Find(x => x.ID.Equals("center")).Text = LanguageHelper.GetTranslation(language, "LoginStatus_Center");
            user.Sub.Find(x => x.ID.Equals("switch")).Text = LanguageHelper.GetTranslation(language, "LoginStatus_Switch");
            user.Sub.Find(x => x.ID.Equals("logout")).Text = LanguageHelper.GetTranslation(language, "LoginStatus_Logout");
            var leftMenuConsole = menu.Items.Find(x => x.ID.Equals("控制台"));
            leftMenuConsole.Text = LanguageHelper.GetTranslation(language, "Menu_Console");
            foreach (var item in leftMenuConsole.Sub)
            {
                if (item.ID == "RunStatus")
                {
                    item.Text = LanguageHelper.GetTranslation(language, "Menu_Console_RunStatus");
                }
            }
            var leftMenuSystem = menu.Items.Find(x => x.ID.Equals("系统管理"));
            leftMenuSystem.Text = LanguageHelper.GetTranslation(language, "Menu_System");
            foreach (var item in leftMenuSystem.Sub)
            {
                if (item.ID == "UserConfig")
                {
                    item.Text = LanguageHelper.GetTranslation(language, "Menu_System_User");
                }
            }
            var leftMenuDataRecord = menu.Items.Find(x => x.ID.Equals("数据追溯"));
            leftMenuDataRecord.Text = LanguageHelper.GetTranslation(language, "Menu_Data");
            foreach (var item in leftMenuDataRecord.Sub)
            {
                if (item.ID == "LogRecord")
                {
                    item.Text = LanguageHelper.GetTranslation(language, "Menu_Data_Log");
                }
            }
        }

        private void InitData()
        {
            //LogRecord logRecord = new LogRecord()
            //{
            //    DeviceType = "风机",
            //    Level = "Info",
            //    Logger = nameof(InitData),
            //    Message = "创建数据表"
            //};
            //DBHelper.HistoryDbContext.Insert(logRecord).ExecuteInserted();
            control = new Wellcome { Dock = DockStyle.Fill };
            AutoDpi(control);
            panel_content.Controls.Add(control);
        }

        private void BindEventHandler()
        {
            buttonSZ.Click += ButtonSZ_Click;
            button_color.Click += Button_color_Click;
            input_search.TextChanged += Input_search_textchanged;
            menu.SelectChanged += Menu_SelectChanged;
            menu_user.SelectChanged += Menu_user_SelectChanged;
            menu_user.Click += Menu_user_Click;
            //监听系统深浅色变化
            SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged;
        }

        private void Input_search_textchanged(object sender, EventArgs e)
        {
            titlebar.Loading = true;
            var text = input_search.Text.ToLower(); // 将输入文本转换为小写，确保搜索不区分大小写
            LoadMenu(text); // 传递搜索文本
            titlebar.Loading = false;
        }

        private void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
        {
            if (e.Category == UserPreferenceCategory.General)
            {
                ThemeHelper.SetColorMode(this, ThemeHelper.IsLightMode());
            }
        }

        private void LoadAppConfig()
        {
            // 读取 appsettings.json 文件
            var appSettings = AppSetting.GetAppSettings();
            // 加载色彩模式
            var value = appSettings["ColorMode"]?.ToString();
            if (value == "Auto")
            {
                ThemeHelper.SetColorMode(this, ThemeHelper.IsLightMode());
            }
            else
            {
                ThemeHelper.SetColorMode(this, value == "Light");
            }

            // 加载动画
            var animation = appSettings["Animation"]?.ToString();
            AntdUI.Config.Animation = animation == "True";

            // 加载阴影
            var shadow = appSettings["ShadowEnabled"]?.ToString();
            AntdUI.Config.ShadowEnabled = shadow == "True";

            // 滚动条
            var scrollbar = appSettings["ScrollBarHide"]?.ToString();
            AntdUI.Config.ScrollBarHide = scrollbar == "True";

            // 窗口内弹出 Message/Notification
            var popup = appSettings["ShowInWindow"]?.ToString();
            AntdUI.Config.ShowInWindow = popup == "True";

            // 通知消息边界偏移量XY（Message/Notification）
            var messageOffset = appSettings["NoticeWindowOffsetXY"]?.ToString();
            AntdUI.Config.NoticeWindowOffsetXY = Convert.ToInt32(messageOffset);
        }

        private void Button_color_Click(object sender, EventArgs e)
        {
            // 读取 appsettings.json 文件
            var appSettings = AppSetting.GetAppSettings();
            var value = appSettings["ColorMode"]?.ToString();
            if (value == "Auto")
            {
                //反向设置
                ThemeHelper.SetColorMode(this, !ThemeHelper.IsLightMode());
                AppSetting.UpdateAppSetting("ColorMode", ThemeHelper.IsLightMode() ? "Dark" : "Light");
            }
            else
            {
                ThemeHelper.SetColorMode(this, value == "Dark");
                AppSetting.UpdateAppSetting("ColorMode", value == "Dark" ? "Light" : "Dark");
            }
        }

        private void ButtonSZ_Click(object sender, EventArgs e)
        {
            using (var form = new SystemSet(this))
            {
                AntdUI.Modal.open(new AntdUI.Modal.Config(this, "系统设置", form, TType.Info)
                {
                    CloseIcon = true,
                    BtnHeight = 0,
                    Keyboard = false,
                    MaskClosable = false,
                });
            }
        }

        private void LoadMenu(string filter = "")
        {
            var task = Task.Run(() =>
             {
                 menu.Items.Clear();
                 foreach (var rootItem in DataUtil.MenuItems)
                 {
                     var rootKey = rootItem.Key.ToLower();
                     var rootMenu = new AntdUI.MenuItem { Text = rootItem.Key, ID = rootItem.Key };
                     bool rootVisible = false; // 用于标记是否显示根节点

                     foreach (var item in rootItem.Value)
                     {
                         if (AppInfo.CurrentUser == null)
                         {
                             if (item.Rank > RoleTypeEnum.Staff)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (item.Rank > AppInfo.CurrentUser.Rank)
                             {
                                 continue;
                             }
                         }
                         var childText = item.Text.ToLower();

                         // 如果子节点包含搜索文本
                         if (childText.Contains(filter))
                         {
                             var menuItem = new AntdUI.MenuItem
                             {
                                 Text = item.Text,
                                 IconSvg = item.IconSvg,
                                 Tag = item.Tag,
                                 ID = item.Tag
                             };
                             rootMenu.Sub.Add(menuItem);
                             rootVisible = true; // 如果有子节点包含，则显示根节点
                         }
                     }
                     // 如果根节点包含搜索文本，或有可见的子节点，则显示根节点
                     if (rootKey.Contains(filter) || rootVisible)
                     {
                         menu.Items.Add(rootMenu);
                     }
                 }
             });
            task.Wait();
            UpdateLanguage(LanguageHelper.CurrentLanguage);
        }

        private void Menu_SelectChanged(object sender, MenuSelectEventArgs e)
        {
            var name = e.Value.Tag;
            panel_content.Controls.Clear();
            switch (name)
            {
                case "DeviceManual":
                    control = new EonfullManual();
                    break;
                case "UserConfig":
                    control = new UserConfig();
                    break;

                case "LogRecord":
                    control = new Views.UserView.LogRecord();
                    break;

                case "UserControlDeviceList":
                    control = new Views.Device.UserControlDeviceList(this);
                    break;

                default:
                    break;
            }
            if (control != null)
            {
                //容器添加控件，需要调整dpi
                control.Dock = DockStyle.Fill;
                AutoDpi(control);
                panel_content.Controls.Add(control);
            }
        }

        private void Menu_user_Click(object sender, EventArgs e)
        {
            if (!AppInfo.IsLogin)
            {
                using (UserLogin user = new UserLogin("用户登录") { Size = new Size(163, 138) })
                {
                    AntdUI.Modal.open(new AntdUI.Modal.Config(Window, "", user, TType.None)
                    {
                        BtnHeight = 0,
                    });
                    if (AppInfo.IsLogin)
                    {
                        var menu = sender as Menu;
                        menu.Items.Find(x => true).Text = AppInfo.CurrentUser.Account;
                        LoadMenu();
                    }
                }
            }
        }

        private void Menu_user_SelectChanged(object sender, MenuSelectEventArgs e)
        {
            if (!AppInfo.IsLogin)
            {
                return;
            }

            var menu = sender as Menu;
            var userMenu = menu.Items.Find(x => x.ID.Equals("LoginStatus")).Sub;
            var activeName = userMenu.Find(x => x.Text == e.Value.ToString()).ID;
            //var activeName = e.Value.ToString();
            switch (activeName)
            {
                case "center":
                    break;

                case "switch":
                    using (UserLogin user = new UserLogin("用户切换") { Size = new Size(163, 138) })
                    {
                        AntdUI.Modal.open(new AntdUI.Modal.Config(Window, "", user, TType.None)
                        {
                            BtnHeight = 0,
                        });
                        if (AppInfo.IsLogin)
                        {
                            menu.Items.Find(x => true).Text = AppInfo.CurrentUser.Account;
                            panel_content.Controls.Clear();
                            LoadMenu();
                        }
                        break;
                    }
                case "logout":
                    AppInfo.IsLogin = false;
                    AppInfo.CurrentUser = null;
                    menu.Items.Find(x => true).Text = "未登录";
                    panel_content.Controls.Clear();
                    LoadMenu();
                    break;

                default:
                    break;
            }
        }
    }
}